#include <48func.h>
typedef struct shareRes_s {
    int ticket;
    pthread_mutex_t mutex;
    int flag; // 用来决定加票是否应该执行
} shareRes_t;
void *sellWindow1(void *arg){
    shareRes_t * pshareRes = (shareRes_t *)arg;
    while(1){
        pthread_mutex_lock(&pshareRes->mutex);
        if(pshareRes->ticket <= 0){
            pthread_mutex_unlock(&pshareRes->mutex);
            break;
        }
        printf("Before window1 sells ticket, ticket = %d\n", pshareRes->ticket);
        --pshareRes->ticket;
        printf("After window1 sells ticket, ticket = %d\n", pshareRes->ticket);
        if(pshareRes->ticket <= 10){
            pshareRes->flag = 1;
        }
        pthread_mutex_unlock(&pshareRes->mutex);
        sleep(1);
    }
    pthread_exit(NULL);
}
void *sellWindow2(void *arg){
    shareRes_t * pshareRes = (shareRes_t *)arg;
    while(1){
        pthread_mutex_lock(&pshareRes->mutex);
        if(pshareRes->ticket <= 0){
            pthread_mutex_unlock(&pshareRes->mutex);
            break;
        }
        printf("Before window2 sells ticket, ticket = %d\n", pshareRes->ticket);
        --pshareRes->ticket;
        printf("After window2 sells ticket, ticket = %d\n", pshareRes->ticket);
        if(pshareRes->ticket <= 10){
            pshareRes->flag = 1;
        }
        pthread_mutex_unlock(&pshareRes->mutex);
        sleep(1);
    }
    pthread_exit(NULL);
}
void * addTicket(void *arg){
    shareRes_t * pshareRes = (shareRes_t *)arg;
    while(1){
        pthread_mutex_lock(&pshareRes->mutex);
        if(pshareRes->flag != 0){
            // 可以加票
            pshareRes->ticket += 10;
            printf("ticket is added!\n");
            pthread_mutex_unlock(&pshareRes->mutex);
            break;
        }
        pthread_mutex_unlock(&pshareRes->mutex);
        usleep(100000);
    }
    pthread_exit(NULL);
}
int main()
{
    shareRes_t shareRes;
    shareRes.ticket = 20;
    shareRes.flag = 0; //一开始不可以加票
    pthread_mutex_init(&shareRes.mutex,NULL);
    pthread_t tid1,tid2,tid3;
    pthread_create(&tid1,NULL,sellWindow1,&shareRes);
    pthread_create(&tid2,NULL,sellWindow2,&shareRes);
    pthread_create(&tid3,NULL,addTicket,&shareRes);
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    pthread_join(tid3,NULL);
    return 0;
}

